package com.m4f.fse.components.impl;

import java.net.URI;
import java.util.Map;
import com.googlecode.objectify.annotation.Subclass;
import com.m4f.fse.components.helpers.GaeHttpContentAcquirer;
import java.net.URLEncoder;

@Subclass
public class GsaSearchEngine extends BaseSearchEngine {
	
	private String url;
	
	private static final String NUM_PARAM = "num";
	private static final String START_PARAM = "start";
	private static final String LANG_PARAM = "hl";
	private static final String OUTPUT_PARAM = "output";
	
	public GsaSearchEngine() {
		super();
	}
	
	public GsaSearchEngine(String url) {
		super();
		this.url = url;
	}

	@Override
	public byte[] search(Map<String, String> params) throws Exception {
		// TODO Auto-generated method stub
		this.completeParams(params);
		String dynamicUrl = this.url + "?";
		for(String key : params.keySet()) {
			String param = key + "=" + URLEncoder.encode(params.get(key), "UTF-8");
			if(key.equals(NUM_PARAM)) {
				param = key + "=1000";
			} else if(key.equals(START_PARAM))  {
				param = key + "=0";
			}
			dynamicUrl += param + "&";
		}
		GaeHttpContentAcquirer acquirer = new GaeHttpContentAcquirer();
		return acquirer.getContent(new URI(dynamicUrl));
	}
	
	private void completeParams(Map<String, String> params) {
		if(!params.containsKey(this.OUTPUT_PARAM)) {
			params.put(this.OUTPUT_PARAM, "xml_no_dtd");
		}
	}
	
	@Override
	public boolean isAcceptable(Map<String, String> params) {
		return this.checkLang(params);
	}
	
	private boolean checkLang(Map<String, String> params) {
		if(!params.containsKey(LANG_PARAM)) {
			return true;
		}
		String lang = params.get(LANG_PARAM);
		if(lang.equals(this.getLang())) {
			return true;
		}
		return false;
	}
	
	
}